/*
 * Container.cpp
 *
 *  Created on: 24-11-2010
 *      Author: Przemek
 */

#include "gui/Container.hpp"
#include "gui/UIManager.hpp"
#include "utils/VectorUtils.hpp"
#include "utils/GLUtils.hpp"
#include "gui/ClipArea.hpp"
#include "pch.hpp"
using namespace boost;

void Container::add(Control* control)
{
	shared_ptr<Control> toAdd = shared_ptr<Control> (control);
	add(toAdd);
}

void Container::remove(Control* control)
{
	ControlsVector::iterator iter = VectorUtils::findInSharedPtrVector<Control>(controls, control);
	if(iter != controls.end())
	{
		controls.erase(iter);
	}
}

Control* Container::getDeepestControlAt(const Vector& point, Vector* pointInControlCoordinates)
{
	const Vector& translatedPoint = point - getPosition();
	if(anyControlAt(translatedPoint))
	{
		Control* candidate = getControlAt(translatedPoint);

		Container* container = dynamic_cast<Container*> (candidate);
		if(container != NULL)
		{
			return container->getDeepestControlAt(translatedPoint, pointInControlCoordinates);
		}
		pointInControlCoordinates->set(translatedPoint - candidate->getPosition());
		return candidate;
	}

	pointInControlCoordinates->set(translatedPoint);
	return this;
}

void Container::draw(const ClipArea& clipArea)
{
	drawChildren(clipArea);
}

void Container::add(shared_ptr<Control>& control)
{
	if(VectorUtils::contains<shared_ptr<Control> >(controls, control) == false)
	{
		controls.push_back(control);
	}
}

bool Container::anyControlAt(const Vector& point) const
{
	return (getControlAt(point) != NULL);
}

Control* Container::getControlAt(const Vector& point) const
{
	BOOST_FOREACH(const shared_ptr<Control>& control, controls)
				{
					Control* c = control.get();
					if(c->getBounds().contains(point))
					{
						return c;
					}
				}
	return 0;
}

void Container::drawChildren(const ClipArea& clipArea)
{
	if(isOpaque())
	{
		GLColor::BLACK.setGLState();
		GLUtils::drawRectangle(Vector(0, 0), getSize());
	}

	BOOST_FOREACH(const shared_ptr<Control>& control, controls)
				{
					ClipArea controlClipArea = clipArea.getUpdatedByControl(*control.get());
					controlClipArea.setGLClipArea();
					drawControl(*control.get(), controlClipArea);
				}
}

